package com.tour.modules.web.until;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.tour.common.utils.R;

public class UpDownUntil {
	/**
	 * 上传工具类
	 * 
	 * 
	 * @param file上传文件
	 * @param fileAdress文件存储地址
	 * @param saveFileName文件存储名,只有名，格式默认为上传格式
	 * @return
	 */
	public R Upload(CommonsMultipartFile file, String fileAdress, String saveFileName, Long fileSize) {
		if (!file.isEmpty()) {

			// 当文件超过设置的大小时，则不运行上传
			if (file.getSize() > fileSize) {

				return R.error("文件太大");
			}
			// 获取文件名后缀
			String OriginalFilename = file.getOriginalFilename();
			String fileSuffix = OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1).toLowerCase();

			// 新文件名
			String newname = "";

			newname += saveFileName + "." + fileSuffix;

			try {
				String pathName = fileAdress + newname;
				// 创建文件
				File saveFile = new File(pathName);

				System.out.println(saveFile);
				// 保存文件
				file.transferTo(saveFile);
				// FileTranser.saveFielByFileName(file, uploadPath, newname);

				return R.ok().put("file", saveFile);
			} catch (Exception e) {

				return R.error("上传文件失败");
			}
		} else {

			return R.error("不能上传空文件");
		}
	}

	/**
	 * 下载工具类
	 * 
	 * 
	 * @param filename下载后显示的名称
	 * @param file下载地址和文件名
	 * @param response
	 * @return
	 */
	public R DownLoad(String filename, String file, HttpServletResponse response) {
		response.reset();
		try {
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
			response.setHeader("Connection", "close");
			response.setHeader("Content-Type", "application/octet-stream");
		} catch (UnsupportedEncodingException e1) {

			e1.printStackTrace();
			return R.error("文件未找到，请联系管理员！");
		}

		OutputStream ops = null;
		FileInputStream fis = null;
		byte[] buffer = new byte[8192];
		int bytesRead = 0;

		try {
			ops = response.getOutputStream();
			// 创建读取文件流
			fis = new FileInputStream(file);
			while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
				ops.write(buffer, 0, bytesRead);
			}
			ops.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (ops != null) {
					ops.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return R.ok();
	}
}
